package com.example.javamaday.reentrantlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock学习（一）
 * <p>
 * 任务：使用ReentrantLock替代synchronized.
 * 注意：必须要注意手动释放锁的逻辑，尤其是异常处理的时候。
 */
public class ReentrantLock1 {

    private Lock lock = new ReentrantLock();

    private void fun1() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void fun2() {
        lock.lock();
        System.out.println("fun2 run.");
        lock.unlock();
    }

    public static void main(String[] args) {
        ReentrantLock1 reentrantLock1 = new ReentrantLock1();
        new Thread(reentrantLock1::fun1).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(reentrantLock1::fun2).start();
    }

}
